﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;

namespace EDTS.Weixin.Submits
{
    public class Submit
    {
        /// <summary>
        /// 取得访问令牌
        /// </summary>
        /// <param name="corpid"></param>
        /// <param name="secrect"></param>
        /// <returns></returns>
        public static string GetAccessToken(string corpid, string secrect)
        {
            var url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
            url = string.Format("{0}?corpid={1}&corpsecret={2}", url, corpid, secrect);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            var obj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(retString);
            return obj.Value<string>("access_token");
        }
        /// <summary>
        /// Get方式访问的接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        public static JObject Get(string token,string url, List<KeyValuePair<string, string>> parameters)
        {
            url = string.Format("{0}?access_token={1}", url, token);
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var p in parameters)
                    url += string.Format("&{0}={1}", p.Key, p.Value);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            var obj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(retString);
            if (obj.Value<int>("errcode") != 0)
                throw new EDTS.Utils.IException(string.Format("微信接口调用失败：",obj.Value<string>("errmsg")));
            return obj;
        }
        /// <summary>
        /// 以Post方式访问的接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static JObject Post(string token,string url, object data)
        {
            url = string.Format("{0}?access_token={1}", url, token);
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            byte[] buffer = Encoding.UTF8.GetBytes(json);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = buffer.Length;
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(buffer, 0, buffer.Length);
            myRequestStream.Flush();
            myRequestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            var obj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(retString);
            if (obj.Value<int>("errcode") != 0)
                throw new EDTS.Utils.IException(string.Format("微信接口调用失败 错误码:{0}, 错误信息：{1}", obj.Value<int>("errcode"), obj.Value<string>("errmsg")));
            return obj;
        }
    }
}
